package com.ruoyi.web.controller.energy;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.energy.domain.EmsEnergyData;
import com.ruoyi.energy.domain.EmsTimeSeriesData;
import com.ruoyi.energy.service.IEmsEnergyDataService;
import com.ruoyi.energy.service.IEmsDeviceDataStatisticsService;
import com.ruoyi.energy.service.ITDengineTimeSeriesService;
import com.ruoyi.common.utils.DateUtils;

/**
 * 数据监控Controller
 * 
 * @author ruoyi
 * @date 2024-01-20
 */
@RestController
@RequestMapping("/energy/monitor")
public class EmsMonitorController extends BaseController {
    
    @Autowired
    private IEmsEnergyDataService emsEnergyDataService;

    @Autowired
    private IEmsDeviceDataStatisticsService statisticsService;

    @Autowired
    private ITDengineTimeSeriesService tdengineTimeSeriesService;

    /**
     * 查询能源数据列表
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/list")
    public TableDataInfo list(EmsEnergyData emsEnergyData,
                             @RequestParam(required = false) String beginTime,
                             @RequestParam(required = false) String endTime) {
        try {
            // 如果没有提供时间范围，使用最近7天
            if (beginTime == null || endTime == null) {
                java.util.Calendar cal = java.util.Calendar.getInstance();
                endTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
                cal.add(java.util.Calendar.DAY_OF_MONTH, -7);
                beginTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
            }

            Date startTime = DateUtils.parseDate(beginTime);
            Date endTimeDate = DateUtils.parseDate(endTime);

            // 获取分页参数
            PageDomain pageDomain = TableSupport.getPageDomain();
            int pageNum = pageDomain.getPageNum();
            int pageSize = pageDomain.getPageSize();
            int offset = (pageNum - 1) * pageSize;

            List<EmsTimeSeriesData> timeSeriesList = new ArrayList<>();
            long total = 0;

            if (emsEnergyData.getDeviceId() != null) {
                // 查询指定设备的历史数据
                // 这里需要根据设备ID获取设备编码
                // 暂时使用设备ID作为设备编码
                String deviceCode = "DEV" + String.format("%03d", emsEnergyData.getDeviceId());
                timeSeriesList = tdengineTimeSeriesService.selectHistoryDataByDeviceWithPage(
                    deviceCode, startTime, endTimeDate, pageSize, offset);
                total = tdengineTimeSeriesService.countDeviceData(deviceCode, startTime, endTimeDate);
            } else {
                // 查询所有设备的最新数据作为列表展示
                List<EmsTimeSeriesData> allLatestData = tdengineTimeSeriesService.selectAllDevicesLatestData();

                // 手动分页
                int start = Math.min(offset, allLatestData.size());
                int end = Math.min(offset + pageSize, allLatestData.size());
                timeSeriesList = allLatestData.subList(start, end);
                total = allLatestData.size();
            }

            // 转换为前端期望的格式
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (EmsTimeSeriesData data : timeSeriesList) {
                Map<String, Object> item = new HashMap<>();
                item.put("dataId", System.currentTimeMillis()); // 临时ID
                item.put("deviceCode", data.getDeviceCode());
                item.put("deviceName", data.getDeviceCode()); // 暂时使用设备编码作为名称
                item.put("energyType", data.getEnergyType());
                item.put("voltage", data.getVoltage());
                item.put("current", data.getCurrent());
                item.put("power", data.getPower());
                item.put("totalEnergy", data.getTotalEnergy());
                item.put("powerFactor", data.getPowerFactor());
                item.put("temperature", data.getTemperature());
                item.put("status", data.getStatus());
                item.put("quality", data.getQuality());
                item.put("ts", data.getTs()); // 修改为ts字段，与前端保持一致
                item.put("collectTime", data.getTs()); // 保留collectTime字段以兼容其他地方
                resultList.add(item);
            }

            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setRows(resultList);
            dataTable.setTotal(total);
            dataTable.setCode(200);
            dataTable.setMsg("查询成功");

            return dataTable;
        } catch (Exception e) {
            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setRows(new ArrayList<>());
            dataTable.setTotal(0);
            dataTable.setCode(500);
            dataTable.setMsg("查询失败: " + e.getMessage());
            return dataTable;
        }
    }

    /**
     * 查询最新能源数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/latest")
    public AjaxResult getLatestData() {
        List<EmsEnergyData> list = emsEnergyDataService.selectLatestDataList();
        return AjaxResult.success(list);
    }

    /**
     * 根据设备ID查询最新数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/latest/{deviceId}")
    public AjaxResult getLatestDataByDevice(@PathVariable("deviceId") Long deviceId) {
        EmsEnergyData data = emsEnergyDataService.selectLatestDataByDeviceId(deviceId);
        return AjaxResult.success(data);
    }

    /**
     * 查询能源数据统计
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics(@RequestParam(value = "deviceId", required = false) Long deviceId,
                                   @RequestParam("startTime") String startTime,
                                   @RequestParam("endTime") String endTime,
                                   @RequestParam(value = "timeType", defaultValue = "hour") String timeType) {
        List<Map<String, Object>> data = emsEnergyDataService.selectEnergyDataStatistics(deviceId, startTime, endTime, timeType);
        return AjaxResult.success(data);
    }

    /**
     * 查询能源数据趋势
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/trend")
    public AjaxResult getTrend(@RequestParam(value = "deviceId", required = false) Long deviceId,
                              @RequestParam(value = "startTime", required = false) String startTime,
                              @RequestParam(value = "endTime", required = false) String endTime) {
        // 如果没有提供时间范围，使用默认的最近24小时
        if (startTime == null || endTime == null) {
            java.util.Calendar cal = java.util.Calendar.getInstance();
            endTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
            cal.add(java.util.Calendar.HOUR, -24);
            startTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
        }

        List<Map<String, Object>> data = emsEnergyDataService.selectEnergyDataTrend(deviceId, startTime, endTime);
        return AjaxResult.success(data);
    }

    /**
     * 导出能源数据列表
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:export')")
    @Log(title = "能源数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmsEnergyData emsEnergyData) {
        List<EmsEnergyData> list = emsEnergyDataService.selectEmsEnergyDataList(emsEnergyData);
        ExcelUtil<EmsEnergyData> util = new ExcelUtil<EmsEnergyData>(EmsEnergyData.class);
        util.exportExcel(response, list, "能源数据");
    }

    /**
     * 获取能源数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:query')")
    @GetMapping(value = "/{dataId}")
    public AjaxResult getInfo(@PathVariable("dataId") Long dataId) {
        return AjaxResult.success(emsEnergyDataService.selectEmsEnergyDataByDataId(dataId));
    }

    /**
     * 新增能源数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:add')")
    @Log(title = "能源数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmsEnergyData emsEnergyData) {
        return toAjax(emsEnergyDataService.insertEmsEnergyData(emsEnergyData));
    }

    /**
     * 批量新增能源数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:add')")
    @Log(title = "能源数据", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult addBatch(@RequestBody List<EmsEnergyData> emsEnergyDataList) {
        return toAjax(emsEnergyDataService.insertEmsEnergyDataBatch(emsEnergyDataList));
    }

    /**
     * 修改能源数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:edit')")
    @Log(title = "能源数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmsEnergyData emsEnergyData) {
        return toAjax(emsEnergyDataService.updateEmsEnergyData(emsEnergyData));
    }

    /**
     * 删除能源数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:remove')")
    @Log(title = "能源数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dataIds}")
    public AjaxResult remove(@PathVariable Long[] dataIds) {
        return toAjax(emsEnergyDataService.deleteEmsEnergyDataByDataIds(dataIds));
    }

    /**
     * 清理历史数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:remove')")
    @Log(title = "清理历史数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/clean/{beforeTime}")
    public AjaxResult cleanHistory(@PathVariable String beforeTime) {
        return toAjax(emsEnergyDataService.cleanHistoryData(beforeTime));
    }

    /**
     * 获取实时监控数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/realtime")
    public AjaxResult getRealtimeMonitorData(@RequestParam(required = false) List<String> deviceCodes) {
        try {
            List<Map<String, Object>> data = statisticsService.getDeviceRealtimeMonitorData(deviceCodes);
            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error("获取设备实时监控数据失败: " + e.getMessage());
        }
    }

    /**
     * 根据设备ID获取实时监控数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/realtime/{deviceId}")
    public AjaxResult getRealtimeDataByDevice(@PathVariable("deviceId") Long deviceId) {
        try {
            // 根据设备ID查询设备编码
            // 这里需要通过设备服务获取设备信息
            // 暂时返回空数据，需要完善
            Map<String, Object> data = new HashMap<>();
            data.put("power", 0.0);
            data.put("voltage", 0.0);
            data.put("current", 0.0);
            data.put("temperature", 0.0);
            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error("获取设备实时监控数据失败: " + e.getMessage());
        }
    }
}